package com.devops.admin.service.impl;

import com.devops.admin.service.*;
import com.devops.admin.util.Assert;
import com.devops.admin.util.K8sClientUtil;
import com.devops.admin.vo.DOSNamespaceChart;
import io.fabric8.kubernetes.client.KubernetesClient;
import io.fabric8.kubernetes.client.dsl.LogWatch;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.*;

/**
 * @ClassName LogService
 * @Description TODO
 * @Author hepingguo
 * @Date 2022/4/27 16:31
 * @Version 1.0
 **/
@Service("logService")
@Slf4j
public class DOSLogServiceImpl implements DOSLogsService {

    @Autowired
    private DOSReleaseService dosReleaseService;
    @Autowired
    private DOSClusterInfoService dosClusterInfoService;
    @Value("${k8s.log.lines}")
    private Integer logLines;
    @Autowired
    DOSReleaseOutService dosReleaseOutService;

    @Override
    public LogWatch getK8sClusterPodLog(int releaseId, String podName, int type) {
        Assert.isTrueMvc(releaseId>0,"releaseId不能为空");
        DOSNamespaceChart namespaceChart;
        if (type == 1) {
            namespaceChart = dosReleaseOutService.getInfoByReleaseId(releaseId);
        }else{
            namespaceChart = dosReleaseOutService.getInfoByResourceId(releaseId);
        }
        Assert.isTrueMvc(null!=namespaceChart,"请检查releaseId是否正确");

        KubernetesClient client = K8sClientUtil.getKubernetesClient(namespaceChart.getConfigPath(),namespaceChart.getConfigContent());
        return client.pods().inNamespace(namespaceChart.getNamespace()).withName(podName).tailingLines(logLines).watchLog();
    }

    @Override
    public void closeK8sClusterPodLog(int releaseId, String podName, PipedOutputStream out, int type) {
        Assert.isTrueMvc(releaseId>0,"releaseId不能为空");
        DOSNamespaceChart namespaceChart;
        if (type == 1) {
            namespaceChart = dosReleaseOutService.getInfoByReleaseId(releaseId);
        }else{
            namespaceChart = dosReleaseOutService.getInfoByResourceId(releaseId);
        }
        Assert.isTrueMvc(null!=namespaceChart,"请检查releaseId是否正确");

        KubernetesClient client = K8sClientUtil.getKubernetesClient(namespaceChart.getConfigPath(),namespaceChart.getConfigContent());
        client.pods().inNamespace(namespaceChart.getNamespace()).withName(podName).tailingLines(logLines).watchLog(out).close();
    }
}
